import java.util.*;

/**
 * @author hewei
 * @version 1.0
 * @description: 1353. 最多可以参加的会议数目
 * @date 2022/11/5 15:49
 */

public class MaxEvents {

    public int maxEvents(int[][] events) {
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> {
            if (a[1] != b[1]) return a[1] - b[1];
            return a[0] - b[0];
        });
        HashMap<Integer, List<int[]>> map = new HashMap<>();
        int max = 0;
        for (int[] event : events) {
            max = Math.max(max, event[1]);
            if (!map.containsKey(event[0])) map.put(event[0], new ArrayList<>());
            map.get(event[0]).add(event);
        }
        int ans = 0;
        for (int i = 1; i <= max; i++) {
            List<int[]> ints = map.get(i);
            if (ints != null) {
                heap.addAll(ints);
            }
            while (!heap.isEmpty() && heap.peek()[1] < i) heap.poll();
            if (!heap.isEmpty()) {
                heap.poll();
                ++ans;
            }
        }
        return ans;
    }
}
